package com.shop.controller;

import com.shop.bean.Product;
import com.shop.bean.User;
import com.shop.service.IUserService;
import com.shop.util.LayData;
import com.shop.util.Page;
import com.shop.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    IUserService userService;

    @RequestMapping("getuserinfo")
    @ResponseBody
    public LayData getLoginUser(HttpSession session){
        User loginuser=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        if(loginuser==null){
            throw new RuntimeException("未登录");
        }

        int id=loginuser.getId();
        User user=userService.getUserByID(id);
        return LayData.success(200,"",user);
    }
    @RequestMapping("edit")
    @ResponseBody
    public LayData editUser(HttpSession session,User user){
        if(user.getId()==0){
            User loginuser=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
            int id=loginuser.getId();
            user.setId(id);
        }
        userService.editUser(user);
        return LayData.success(200,null);
    }
    @RequestMapping("getuserbyusername")
    @ResponseBody
    public LayData getUserByUsername(User user){
        User userData=userService.getUser(user);
        return LayData.success(userData);
    }

    @RequestMapping("changePassword")
    @ResponseBody
    public LayData changePassword(HttpSession session,String newpassword,String oldpassword,String confirmpassword){


        User loginuser = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        int id = loginuser.getId();
        userService.changePassword(id,newpassword,oldpassword,confirmpassword);

        return LayData.success(200, "修改成功");
    }

    @RequestMapping("reloadPassword")
    @ResponseBody
    public LayData reloadPassword(Integer id){
        userService.reloadPassword(id);
        return LayData.success(200, "修改成功");
    }

    @RequestMapping("list")
    @ResponseBody
    public LayData getList(Page page, String text) {
        List<User> list=userService.selectUsers(page, text);
        int count=userService.getCount(text);
        return new LayData(count, list);
    }

    @RequestMapping("delete")
    @ResponseBody
    public LayData delete(Integer id) {
        if (userService.getUserByID(id) != null) {
            userService.deleteUser(id);
        }
        return new LayData(200,"删除成功！！！",1,id);
    }




}
